package com.wande.dataplatform.filecollection.source.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wande.common.core.exception.ServiceException;
import com.wande.dataplatform.filecollection.common.constant.FileCollectionConstants;
import com.wande.dataplatform.filecollection.source.IFileSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 本地文件来源实现
 *
 * @author wande
 */
@Slf4j
@Component
public class LocalFileSource implements IFileSource {

    @Override
    public String getSupportedSourceType() {
        return FileCollectionConstants.SourceType.LOCAL;
    }

    @Override
    public List<String> listFiles(String config) {
        JSONObject configJson = JSONUtil.parseObj(config);
        String path = configJson.getStr("path");
        String pattern = configJson.getStr("pattern", "*");

        File dir = new File(path);
        if (!dir.exists() || !dir.isDirectory()) {
            throw new ServiceException("目录不存在: " + path);
        }

        List<String> files = new ArrayList<>();
        File[] fileArray = dir.listFiles((dir1, name) -> matchPattern(name, pattern));
        if (fileArray != null) {
            for (File file : fileArray) {
                if (file.isFile()) {
                    files.add(file.getAbsolutePath());
                }
            }
        }

        log.info("列出本地文件, path={}, count={}", path, files.size());
        return files;
    }

    @Override
    public InputStream getFileStream(String config, String filePath) {
        try {
            return new FileInputStream(filePath);
        } catch (FileNotFoundException e) {
            throw new ServiceException("文件不存在: " + filePath);
        }
    }

    @Override
    public long getFileSize(String config, String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new ServiceException("文件不存在: " + filePath);
        }
        return file.length();
    }

    @Override
    public boolean testConnection(String config) {
        try {
            JSONObject configJson = JSONUtil.parseObj(config);
            String path = configJson.getStr("path");
            File dir = new File(path);
            return dir.exists() && dir.isDirectory();
        } catch (Exception e) {
            log.error("测试本地文件连接失败", e);
            return false;
        }
    }

    /**
     * 匹配文件名模式
     */
    private boolean matchPattern(String fileName, String pattern) {
        if ("*".equals(pattern)) {
            return true;
        }
        // 简单的通配符匹配
        String regex = pattern.replace(".", "\\.").replace("*", ".*");
        return fileName.matches(regex);
    }
}
